import downLoadVideo from '@/components/downLoadVideo.js'
import { ElMessage } from 'element-plus'

export default async function RecordVideo(index, playList) {
  const id = document.getElementById('artId' + (index + 1)).querySelector('video')
  const stream = id.captureStream() //获取音频/视频api
  const videoTrack = stream.getVideoTracks()[0] //视频流
  const videoStream = new MediaStream([videoTrack]) //创建静音实例
  playList[index].mediaRecorder = new MediaRecorder(
    playList[index].artRef?.muted ? videoStream : stream,
  )
  let timer = null
  timer = setInterval(() => {
    playList[index].recordTime++
  }, 1000) //初始化开启定时器
  await checkChuck(playList[index].mediaRecorder) //初始化执行
  //检查音量
  playList[index].checkMuted = () => {
    playList[index].mediaRecorder = new MediaRecorder(
      playList[index].artRef?.muted ? videoStream : stream,
    )
    checkChuck(playList[index].mediaRecorder)
  }

  function formatterTime(timer) {
    const minutes = Math.floor(timer / 60)
    const seconds = timer % 60
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
  }

  //共用的方法
  async function checkChuck(record) {
    record.ondataavailable = (e) => {
      if (e.data.size > 0) {
        playList[index].recordedChunks.push(e.data)
      }
      playList[index].artRef.layers.update({
        name: 'recordVideo',
        html: `<div class="recordBtn"><div>录屏中${formatterTime(playList[index].recordTime)}</div><img src="/src/assets/images/RecordLoading.png" alt="" style="width: 16px;height: 16px"/></div>`,
        style: {
          margin: '0 auto',
        },
      })
    }
    record.onpause = () => {
      clearInterval(timer)
    }
    record.onresume = () => {
      timer = setInterval(() => {
        playList[index].recordTime++
      }, 1000)
    }
    record.onstop = async () => {
      await downLoadVideo(playList, index)
      clearInterval(timer)
      timer = null
      playList[index].recordTime = 0
      playList[index].recordedChunks = []
      console.log('录屏结束')
      playList[index].artRef.layers.remove('recordVideo')
    }
    try {
      await record.start(1000 / 25)
      playList[index].isRecording = true
      console.log('录屏开始')
    } catch (error) {
      ElMessage.error(error.message)
    }
  }
}
